import { WECHAT, WECHAT_MINI_PROGRAM } from 'cc/env';
import { BaseHandler } from './BaseHandler';
import { Adsdk } from '../../scenes/Adsdk';

export class VideoHandler extends BaseHandler {
    
    /** 激励视频实例 */
    video: any = null

    init() {
        console.log('初始化视频广告')
        this.video = this.basePlatform.platform.createRewardedVideoAd({
            adUnitId: Adsdk.instance.videoAdId,
        })
        if (this.video == null || this.video == undefined) {
            return
        }
        this.video.onError((res) => {
            if (WECHAT || WECHAT_MINI_PROGRAM) {
                if (res.errCode) {
                    if (res.errCode == 1004) {
                        this.basePlatform.platform.showToast({
                            title: '暂无可用广告'
                        })
                    } else {
                        this.basePlatform.platform.showToast({
                            title: '广告出现问题'
                        })
                    }
                }
            }
        })
        this.video.load()
        console.log('激励广告组件加载完毕')
    }

    /**
     * 展示激励视频
     * @param success 完播回调后执行
     * @param share 是否是分享
     * @param fail 分享失败时执行
     */
    show(success: () => void, fail?: () => void, complete?: () => void, share = false) {
        console.log('显示视频广告')
        if (this.video == null) {
            success()
        } else {
            if (share) {
                //分享逻辑
            } else {
                // this.basePlatform.platform.showLoading({
                //     title: "加载中",
                // })
                let handler = (res) => {
                    if (res.count && res.count > 0) {
                        success()
                    } else {
                        if (fail) {
                            fail()
                        }
                    }
                    // this.basePlatform.platform.hideLoading()
                    this.video.offClose(handler)
                    if (complete) {
                        complete()
                    }
                }
                this.video.onClose(handler)
                this.video.show()
            }
        }
    }
}


